package com.starsmark;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * . 请求工具类
 */

public final class HttpClientUtil {

    private static final int CONN_TIME = 15000;
    private static final int RES_TIME = 60000;
    private static final int REQ_SUCCESS = 200;

    private HttpClientUtil() {
    }

    /**
     * . GET
     * @param url
     * @return
     */
    public static String doGet(String url) {
        String result = null;

        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;

        try {
            URL urlObj = new URL(url);
            connection = (HttpURLConnection) urlObj.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(CONN_TIME);
            connection.setReadTimeout(RES_TIME);

            connection.connect();

            if (connection.getResponseCode() == REQ_SUCCESS) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }

                result = sbf.toString();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();
        }

        return result;
    }

}
